/**
 * swfupload general style progress bar
 *
 * @author  Yellow.Chow <aultoale@gmail.com>
 * @version $Id: progress.js 17 2013-04-02 03:28:47Z zhouyonglong $
 * @license http://www.gnu.org/licenses/gpl-3.0.html    GPL 3
 */
var SWFU_timer;

function SWFU_Progress(file, targetElement){
    this.file = file;
    this.target = targetElement;
    this.error = false;

    if (this.file.name.length > 35) {
        this.file.name = this.file.name.substring(0, 20) + "…" +
                         this.file.name.substring(this.file.name.lastIndexOf('.'));
    }

    var size = (this.file.size / 1024).toFixed(1);
    if (size > 1200) {
        size = (size / 1024).toFixed(1);
        if (size > 1200) {
            size = (size / 1024).toFixed(1);
            size += ' GB';
        }
        size += ' MB';
    } else {
        size += ' KB';
    }

    if (this.target.find('.info span').length <= 0) {
        this.target.html(
            '<div class="bar"><div class="status" style="width:0%"></div></div>' +
            '<div class="info">' + this.file.name + ' (' + size +') - <span>' +
            '<font color="gray">准备上传…</font></span></div>'
        )
    }
    this.target.show();
}

SWFU_Progress.prototype.fadeOut = function(ms){
    var element = this.target;
    if (typeof SWFU_timer == 'number') {
        clearTimeout(SWFU_timer);
    }
    SWFU_timer = setTimeout(function(){ element.fadeOut('slow'); }, ms);
    return this;
};

SWFU_Progress.prototype.update = function(bytesLoaded){
    if (this.error == false) {
        var percent = Math.ceil((bytesLoaded / this.file.size) * 100) + '%';
        this.target.find('.info span').html(percent);
        this.target.find('.bar .status').width(percent);
    }
    return this;
};

SWFU_Progress.prototype.complete = function(){
    if (this.error == false) {
        this.target.find('.info').html(this.file.name + ' &nbsp; <font color="green">(上传成功！)</font>');
        this.fadeOut(2000);
    }
    return this;
};

SWFU_Progress.prototype.setError = function(message) {
    this.error = true;
    this.target.find('.info').html(this.file.name + ' &nbsp; <font color="red">(上传失败：' + message + ')</font>');
    this.target.find('.bar').addClass('error');
    this.fadeOut(10000);
    return this;
};